<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统安装</title>
    <script src="/static/js/jquery/jquery.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f1f1f1;
            margin: 0;
            padding: 20px 0;
        }

        .install-container {
            background: white;
            max-width: 700px;
            margin: 0 auto;
            padding: 40px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.13);
        }

        h1 {
            font-size: 24px;
            margin: 0 0 25px;
            font-weight: 400;
            color: #23282d;
        }

        h2 {
            font-size: 18px;
            margin: 25px 0 15px;
            font-weight: 600;
            color: #23282d;
        }

        p {
            line-height: 1.6;
            margin-bottom: 15px;
            color: #444;
        }

        ol, ul {
            margin: 15px 0;
            padding-left: 25px;
        }

        li {
            margin-bottom: 5px;
        }

        code {
            background: #f9f9f9;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: Consolas, Monaco, monospace;
        }

        .form-table {
            width: 100%;
            margin-bottom: 20px;
            border-collapse: collapse;
        }

        .form-table th {
            width: 140px;
            padding: 15px 10px 15px 0;
            text-align: left;
            vertical-align: top;
            font-weight: 600;
            color: #23282d;
        }

        .form-table td {
            padding: 15px 0;
        }

        .form-table input[type="text"],
        .form-table input[type="password"],
        .form-table input[type="email"] {
            width: 100%;
            max-width: 300px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 14px;
            background: #fff;
        }

        .form-table input:focus {
            border-color: #007cba;
            outline: none;
            box-shadow: 0 0 0 1px #007cba;
        }

        .form-table input.success {
            border-color: #46b450;
            box-shadow: 0 0 0 1px #46b450;
        }

        .form-table input.error {
            border-color: #dc3232;
            box-shadow: 0 0 0 1px #dc3232;
        }

        .connection-status {
            margin-top: 5px;
            font-size: 12px;
        }

        .status-success {
            color: #46b450;
        }

        .status-error {
            color: #dc3232;
        }

        .status-checking {
            color: #007cba;
        }

        .button {
            background: #007cba;
            border: 1px solid #007cba;
            color: #fff;
            text-decoration: none;
            padding: 8px 12px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
            display: inline-block;
            line-height: 1.4;
        }

        .button:hover {
            background: #005a87;
            border-color: #005a87;
            color: #fff;
        }

        .button:disabled {
            background: #ccc;
            border-color: #ccc;
            cursor: not-allowed;
        }

        .button-large {
            padding: 12px 24px;
            font-size: 16px;
        }

        .notice {
            background: #fff;
            border-left: 4px solid #fff;
            box-shadow: 0 1px 1px 0 rgba(0,0,0,.1);
            margin: 20px 0;
            padding: 12px;
        }

        .notice-error {
            border-left-color: #dc3232;
        }

        .notice p {
            margin: 0.5em 0;
            padding: 2px;
        }

        .notice ul {
            margin: 10px 0;
        }

        .step {
            margin: 20px 0;
        }

        @media (max-width: 768px) {
            .install-container {
                margin: 10px;
                padding: 20px;
            }

            .form-table th {
                width: auto;
                display: block;
                padding-bottom: 5px;
            }

            .form-table td {
                display: block;
                padding-top: 5px;
            }

            .form-table input[type="text"],
            .form-table input[type="password"],
            .form-table input[type="email"] {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="install-container">
<h1>欢迎使用</h1>
<p>欢迎使用骑士CMS内容管理系统！在开始之前，我们需要一些数据库信息。您需要知道以下信息才能继续。</p>

<ol>
    <li>数据库名</li>
    <li>数据库用户名</li>
    <li>数据库密码</li>
    <li>数据库主机</li>
</ol>

<p>我们将使用这些信息创建一个配置文件。如果由于某种原因自动创建不起作用，不用担心。您所需要做的就是在文本编辑器中打开配置文件，填写您的数据库信息，并保存为<code>.env</code>。</p>

{if condition="$hasErrors"}
<div class="notice notice-error">
    <p><strong>环境检测失败</strong></p>
    <p>在继续之前，请解决以下问题：</p>
    <ul>
        {volist name="failedChecks" id="check"}
        <li><strong>{$check.name}</strong>: 要求 {$check.required}，当前 {$check.current}</li>
        {/volist}
    </ul>
    <p><a href="/install" class="button">重新检测</a></p>
</div>
{else}

<form id="installForm" method="post">
    <table class="form-table">
        <tr>
            <th scope="row"><label for="db_name">数据库名</label></th>
            <td>
                <input name="db_name" id="db_name" type="text" size="25" value="" required />
                <div id="db_name_status" class="connection-status"></div>
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="db_user">数据库用户名</label></th>
            <td>
                <input name="db_user" id="db_user" type="text" size="25" value="" required />
                <div id="db_user_status" class="connection-status"></div>
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="db_password">数据库密码</label></th>
            <td>
                <input name="db_password" id="db_password" type="password" size="25" value="" />
                <div id="db_password_status" class="connection-status"></div>
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="db_host">数据库主机</label></th>
            <td>
                <input name="db_host" id="db_host" type="text" size="25" value="localhost" required />
                <div id="db_host_status" class="connection-status"></div>
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="db_port">端口</label></th>
            <td>
                <input name="db_port" id="db_port" type="text" size="25" value="3306" />
                <div id="db_port_status" class="connection-status"></div>
            </td>
        </tr></table>

    <div id="connection-result" class="notice" style="display: none;">
        <p id="connection-message"></p>
    </div>
    </table>

    <h2>管理员账户</h2>
    <p>请设置管理员账户信息：</p>

    <table class="form-table">
        <tr>
            <th scope="row"><label for="admin_username">管理员用户名</label></th>
            <td><input name="admin_username" id="admin_username" type="text" size="25" value="" required /></td>
        </tr>
        <tr>
            <th scope="row"><label for="admin_password">管理员密码</label></th>
            <td><input name="admin_password" id="admin_password" type="password" size="25" value="" required /></td>
        </tr>
        <tr>
            <th scope="row"><label for="admin_email">管理员邮箱</label></th>
            <td><input name="admin_email" id="admin_email" type="email" size="25" value="" /></td>
        </tr>
    </table>

    <p class="step"><input name="submit" type="submit" value="提交" class="button button-large" id="submitBtn" /></p>
</form>
{/if}

<script>
$(document).ready(function() {
    let connectionTimer = null;
    let lastConnectionData = null;
    let hasValidConnection = false;
    let databaseHasData = false;

    // 数据库连接字段
    const dbFields = ['db_host', 'db_port', 'db_name', 'db_user', 'db_password'];

    // 监听数据库字段变化
    dbFields.forEach(function(field) {
        $('#' + field).on('input', function() {
            clearTimeout(connectionTimer);
            connectionTimer = setTimeout(testConnection, 1000); // 1秒后测试连接
        });
    });

    // 测试数据库连接
    function testConnection() {
        const data = {};
        let hasRequired = true;

        // 收集数据库连接信息
        dbFields.forEach(function(field) {
            data[field] = $('#' + field).val();
            if ((field === 'db_host' || field === 'db_name' || field === 'db_user') && !data[field]) {
                hasRequired = false;
            }
        });

        // 清除之前的状态
        clearConnectionStatus();

        if (!hasRequired) {
            hasValidConnection = false;
            updateSubmitButton();
            return;
        }

        // 显示检测中状态
        showConnectionStatus('checking', '正在检测数据库连接...');

        $.post('/install/test-connection', data)
            .done(function(response) {
                if (response.code === 0) {
                    hasValidConnection = true;
                    databaseHasData = response.hasData;

                    if (response.hasData) {
                        showConnectionStatus('success',
                            '数据库连接成功！检测到数据库中已有 ' + response.tableCount + ' 个表，安装将覆盖现有数据。');
                    } else {
                        showConnectionStatus('success', '数据库连接成功！数据库为空，可以安装。');
                    }

                    // 设置输入框为成功状态
                    dbFields.forEach(function(field) {
                        $('#' + field).removeClass('error').addClass('success');
                    });
                } else {
                    hasValidConnection = false;
                    showConnectionStatus('error', response.msg);

                    // 设置输入框为错误状态
                    dbFields.forEach(function(field) {
                        $('#' + field).removeClass('success').addClass('error');
                    });
                }
                updateSubmitButton();
            })
            .fail(function() {
                hasValidConnection = false;
                showConnectionStatus('error', '网络请求失败，请重试');
                updateSubmitButton();
            });
    }

    // 显示连接状态
    function showConnectionStatus(type, message) {
        const $result = $('#connection-result');
        const $message = $('#connection-message');

        $result.removeClass('notice-success notice-error notice-warning').show();
        $message.removeClass('status-success status-error status-checking');

        if (type === 'success') {
            $result.addClass('notice-success');
            $message.addClass('status-success');
        } else if (type === 'error') {
            $result.addClass('notice-error');
            $message.addClass('status-error');
        } else if (type === 'checking') {
            $result.addClass('notice-warning');
            $message.addClass('status-checking');
        }

        $message.text(message);
    }

    // 清除连接状态
    function clearConnectionStatus() {
        $('#connection-result').hide();
        dbFields.forEach(function(field) {
            $('#' + field).removeClass('success error');
        });
    }

    // 更新提交按钮状态
    function updateSubmitButton() {
        const $btn = $('#submitBtn');
        if (hasValidConnection) {
            $btn.prop('disabled', false);
            if (databaseHasData) {
                $btn.val('覆盖安装');
            } else {
                $btn.val('开始安装');
            }
        } else {
            $btn.prop('disabled', true).val('请先配置数据库连接');
        }
    }

    // 表单提交
    $('#installForm').submit(function(e) {
        e.preventDefault();

        if (!hasValidConnection) {
            alert('请先配置正确的数据库连接');
            return;
        }

        // 如果数据库有数据，确认覆盖安装
        if (databaseHasData) {
            if (!confirm('数据库中已有数据，继续安装将覆盖现有数据。确定要继续吗？')) {
                return;
            }
        }

        const btn = $('#submitBtn');
        const formData = $(this).serializeArray();
        const data = {};
        formData.forEach(item => {
            data[item.name] = item.value;
        });

        // 验证密码
        if (data.admin_password.length < 6) {
            alert('管理员密码长度至少6位');
            return;
        }

        btn.prop('disabled', true).val('安装中...');

        // 先保存配置
        $.post('/install/config', data)
            .done(function(response) {
                if (response.code === 0) {
                    // 执行安装，同时传递配置数据作为备份
                    $.post('/install/install', data)
                        .done(function(response) {
                            if (response.code === 0) {
                                // 使用返回的令牌跳转到完成页面
                                window.location.href = '/install/complete?token=' + response.token;
                            } else {
                                alert('安装失败: ' + response.msg);
                                btn.prop('disabled', false).val(databaseHasData ? '覆盖安装' : '开始安装');
                            }
                        })
                        .fail(function() {
                            alert('安装过程中发生错误，请重试');
                            btn.prop('disabled', false).val(databaseHasData ? '覆盖安装' : '开始安装');
                        });
                } else {
                    alert('配置保存失败: ' + response.msg);
                    btn.prop('disabled', false).val(databaseHasData ? '覆盖安装' : '开始安装');
                }
            })
            .fail(function() {
                alert('网络请求失败，请重试');
                btn.prop('disabled', false).val(databaseHasData ? '覆盖安装' : '开始安装');
            });
    });

    // 初始化按钮状态
    updateSubmitButton();
});
</script>
    </div>
</body>
</html>
